﻿using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace PortalCurriculo.Util.CustomControls.ListViewObjects
{
    public class LayoutTemplate : ITemplate
    {
        public LayoutTemplate(List<Field> fields, TableStructure tableStructure)
        {
            Fields = fields;
            TableStructure = tableStructure;
        }

        public List<Field> Fields { get; set; }
        public TableStructure TableStructure { get; set; }

        #region ITemplate Members

        public void InstantiateIn(Control container)
        {
            Table table = CreateTable();
            var headerRow = new TableHeaderRow();

            foreach (Field field in Fields)
            {
                var headerCell = new TableHeaderCell
                                     {
                                         AbbreviatedText = field.AbbreviatedText,
                                         CssClass = field.CssClass,
                                         //AssociatedHeaderCellID = new[] {field.Name}
                                     };
                headerCell.Attributes.Add("id", field.DisplayName);
                headerCell.Controls.Add(new Label {Text = field.DisplayName, ID = string.Concat("lbl", field.Name)});
                headerRow.Cells.Add(headerCell);
            }

            table.Rows.Add(headerRow);

            var row = new TableRow();
            var cell = new TableCell();
            cell.Controls.Add(new PlaceHolder {ID = "phItem"});
            row.Cells.Add(cell);
            table.Rows.Add(row);

            container.Controls.Add(table);
        }

        private Table CreateTable()
        {
            if (TableStructure == null) return new Table(); 
            
            var table = new Table();
            table.Attributes.Add("summary", TableStructure.Summary);
            table.Caption = TableStructure.Caption;
            table.CssClass = TableStructure.CssClass;
            table.CaptionAlign = TableCaptionAlign.Left;
            return table;
        }

        #endregion
    }
}